package com.xinsilu.hospital.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xinsilu.hospital.entity.AuthsysPermission;
import com.xinsilu.hospital.entity.AuthsysRole;
import com.xinsilu.hospital.entity.AuthsysUser;
import com.xinsilu.hospital.mapper.AuthsysUserMapper;
import com.xinsilu.hospital.service.IAuthsysPermissionService;
import com.xinsilu.hospital.service.IAuthsysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ym
 * @since 2021-11-30
 */
@Service
public class AuthsysUserServiceImpl extends ServiceImpl<AuthsysUserMapper, AuthsysUser> implements IAuthsysUserService {
    @Autowired
    private AuthsysUserMapper userMapper;
    @Autowired
    private IAuthsysPermissionService permissionService;

    @Override
    public AuthsysUser findByUserName(String username) {
        return this.userMapper.selectByUserName(username);
    }

    @Override
    public List<AuthsysUser> findAll() {
        return this.userMapper.selectAll();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void assignUserRoles(AuthsysUser user) {
        this.userMapper.unassignRoles(user.getUrId());
        List<AuthsysRole> roleList = user.getRoleList();
        if(roleList != null){
            for(AuthsysRole role:roleList) {
                this.userMapper.assignRole(user.getUrId(), role.getRlId());
            }
        }
    }

    @Override
    public List<String> getUserPermssions(String username) {
        List<String> permList = null;

        List<AuthsysPermission> permissionList = this.permissionService.searchUserPermissions(username);
        if(permissionList != null){
            permList = new ArrayList<>();
            for(AuthsysPermission perm:permissionList){
                permList.add(perm.getResources().getRscUrl()+":"+perm.getOperator().getOptUrl()+":*");
            }
        }
        return permList;
    }
}
